<?php

/**
 * Global helpers file with misc functions.
 */
if (! function_exists('app_name')) {
    /**
     * Helper to grab the application name.
     *
     * @return mixed
     */
    function app_name()
    {
        return config('app.name');
    }
}

if (! function_exists('access')) {
    /**
     * Access (lol) the Access:: facade as a simple function.
     */
    function access()
    {
        return app('access');
    }
}

if (! function_exists('history')) {
    /**
     * Access the history facade anywhere.
     */
    function history()
    {
        return app('history');
    }
}

if (! function_exists('gravatar')) {
    /**
     * Access the gravatar helper.
     */
    function gravatar()
    {
        return app('gravatar');
    }
}

if (! function_exists('includeRouteFiles')) {

    /**
     * Loops through a folder and requires all PHP files
     * Searches sub-directories as well.
     *
     * @param $folder
     */
    function includeRouteFiles($folder)
    {
        $directory = $folder;
        $handle = opendir($directory);
        $directory_list = [$directory];

        while (false !== ($filename = readdir($handle))) {
            if ($filename != '.' && $filename != '..' && is_dir($directory.$filename)) {
                array_push($directory_list, $directory.$filename.'/');
            }
        }

        foreach ($directory_list as $directory) {
            foreach (glob($directory.'*.php') as $filename) {
                require $filename;
            }
        }
    }
}

if (! function_exists('getRtlCss')) {

    /**
     * The path being passed is generated by Laravel Mix manifest file
     * The webpack plugin takes the css filenames and appends rtl before the .css extension
     * So we take the original and place that in and send back the path.
     *
     * @param $path
     *
     * @return string
     */
    function getRtlCss($path)
    {
        $path = explode('/', $path);
        $filename = end($path);
        array_pop($path);
        $filename = rtrim($filename, '.css');

        return implode('/', $path).'/'.$filename.'.rtl.css';
    }
}

if (! function_exists('json_format')) {
    /**
     * Format json, validate the response
     */
    function json_format($data, $ret = 1, $info = '') {
        if(empty($data)) {
            $data = new \stdClass;
        }
        return array(
            'ret' => $ret,
            'data' => $data,
            'info' => $info
        );
    }
}

if (! function_exists('output')) {
    function output($data = [], $info = '') {
        return json_format($data, 1, $info);
    }
}

if (! function_exists('error')) {
    function error($info = '', $data = [], $code = 0) {
        return json_format($data, $code, $info);
    }
}

if (! function_exists('exception')) {
    function exception($info = '') {
        throw new \App\Exceptions\ServiceErrorException($info);
    }
}

if (! function_exists('expire')) {
    function expire($info = '') {
        throw new \App\Exceptions\ExpireErrorException($info);
    }
}

if (! function_exists('upload')) {
    function upload($file) {
        $image_folder = '/files';

        if(!is_dir($image_folder)) {
            @mkdir($image_folder);
        }

        $image_path   = public_path($image_folder);
        $extension = $file->extension();
        $filename = md5(time(). '-' . $file->name->getClientOriginalName()) .".".$extension ;
        $file->move($image_path, $filename);
        $path = "$image_folder/$filename";

        return $path;
    }
}

if (! function_exists('fileUrl')) {
    function fileUrl($path) {
        if (strpos($path, config('app.url')) === 0 || strpos($path, 'http') === 0 || $path == '') {
            return $path;
        }

        return Storage::disk('upload')->url($path);
    }
}

if (! function_exists('fileUrlExists')) {
    function fileUrlExists($file) {
        if (strpos($file, 'http') === 0) {
            return $file;
        }

        return Storage::disk('upload')->exists($file);
    }
}

if (! function_exists('validatePhone')) {
    function validatePhone($phone) {
        return preg_match("/^1[34578]\d{9}$/", $phone);
    }
}

if (! function_exists('getLoginWxUserId')) {
    function getLoginWxUserId() {
        return $GLOBALS['wx_user_session']['wechat_user_id'] ?? 0;
    }
}

if (! function_exists('getWeekRange')) {
    function getWeekRange() {
        $first = 1; // 1 表示每周星期一为开始日期 0表示每周日为开始日期
        $w = date('w');  // 获取当前周的第几天 周日是 0 周一到周六是 1 - 6
        $num = ($w ? $w - $first : 6);
        $start = now()->subDays("{$num}"); //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
        $startDay = $start->toDateString();
        $endDay = $start->addDays('+6 days')->toDateString();
        return [$startDay, $endDay];
    }
}